<!--利率曲线剥离-->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :rules="qryRules" v-show="showSearch">
      <el-row :gutter="12">
        <el-col :span="4">
          <el-form-item label="计算日期">
            <el-date-picker
                v-model="queryParams.refSetDate"
                type="date"
                :style="{width: '100%'}"
                value-format="YYYY-MM-DD"
                @change="handleQuery"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="利率曲线">
            <el-select v-model="queryParams.ircCode" placeholder="利率曲线"
                       ref="irCurveRef"
                       size="small"
                       @focus="getCurveCodeList()"
                       @change="handleQuery"
                       filterable="true" default-first-option
                       :style="{width: '100%'}">
              <el-option
                  v-for="item in curveCodeList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-form-item>
            <el-button type="primary" icon="Search" size="small" v-hasPermi="['curve:ircurve:ircurvestrip:list']"
            style="margin: 3px 3px" @click="handleQuery">搜索
            </el-button>
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button v-if="calTime!=null"
                     type="success"
                     style="margin: 3px 5px"
                     disabled="true"
                     size="small"
          >{{ calTime }}
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['marketdata:irCurve:add']"
            icon="Plus"
            size="small"
            style="margin: 3px 3px"
            type="primary"
            @click="handleAdd"
        >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['marketdata:irCurve:update']"
            style="margin: 3px 3px"
            icon="Edit"
            size="mini"
            :disabled="updateOpen"
            type="primary"
            @click="handleUpdate"
        >修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['marketdata:irCurve:delete']"
            style="margin: 3px 3px"
            icon="Delete"
            size="mini"
            :disabled="updateOpen"
            type="danger"
            @click="handleDelete"
        >删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            style="margin: 3px 3px"
            size="small"
            @click="handleImport"
          >导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            style="margin: 3px 3px"
            icon="Download"
            size="small"
            @click="handleExport"
            v-hasPermi="['curve:ircurve:ircurvestrip:export']"
        >导出</el-button>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="1" v-loading="loading">
      <el-col :span="12">
        <xTable ref="ircurvestripRef" multiple="false" refId="ircurvestripRef" :data="irCrvStripList"
                @selection-change="handleSelectionChange">
          <template #columList>
            <el-table-column label="序号" type="index" width="50">
            </el-table-column>
            <el-table-column label="曲线代码" align="center" prop="ircCode" v-if="false" width="150"/>
            <el-table-column label="日期" align="center" prop="limitDate" v-if="false" width="150"/>
            <el-table-column label="期限" align="center" prop="ircTerm" width="150"/>
            <el-table-column label="利率(%)" align="center" prop="ircRate" :formatter="formartTablePercentP3"
                             width="150"/>
            <el-table-column label="生效日期" align="center" prop="begDate" width="100"/>
            <el-table-column label="失效日期" align="center" prop="endDate" width="100"/>
          </template>
        </xTable>
      </el-col>
      <el-col :span="12">
        <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
          <IrCurveChart ref="lineChartForm" :chartData="lineChartData"/>
        </el-row>
      </el-col>
    </el-row>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="30%" :close-on-click-modal="false" append-to-body draggable="true">
      <el-form ref="icvstripRef" :model="form" :rules="rules" label-width="80px" size="small">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="利率曲线" prop="ircCode">
              <baseCombox url="/pricing/comboBox/queryIrcurveFilter.action" @blur="productSelect" size="small"
                          placeholder="利率曲线" v-model="form.ircCode" :disabled="true"></baseCombox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="期限" prop="ircTerm">
              <el-input v-model="form.ircTerm" clearable size="small" maxlength="6"
                        placeholder="请输入期限" :disabled="opFlag"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="利率" prop="ircRate">
              <Numberinput v-model="form.ircRate" size="small" maxlength="6" precision="3" append="%"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="生效日期" prop="currency">
              <el-date-picker
                  v-model="form.begDate" :disabled="opFlag"
                  type="date"
                  size="small"
                  value-format="YYYY-MM-DD"
                  placeholder="选择生效日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--对比曲线弹窗-->
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="对比曲线" v-model="compareOpen" width="30%" :close-on-click-modal="false" append-to-body draggable="true">
      <el-form ref="icvstripComRef" :model="compareForm" :rules="compareRules" label-width="80px">
        <el-row :gutter="10">
          <el-col :span="24">
            <el-form-item label="利率曲线" prop="ircCode">
              <baseCombox url="/pricing/comboBox/queryIrcurveFilter.action" size="small"
                          placeholder="利率曲线" v-model="compareForm.ircCode"></baseCombox>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="日期" prop="compareDate">
              <el-date-picker
                  v-model="compareForm.compareDate"
                  type="date"
                  size="small"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCompareForm">确 定</el-button>
          <el-button @click="cancelCompare">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog :title="upload.title" :close-on-click-modal="false" draggable="true" v-model="upload.open" width="400px"
               append-to-body>
      <el-upload
          ref="uploadRef"
          :limit="1"
          accept=".xlsx, .xls"
          :headers="upload.headers"
          :action="upload.url"
          :disabled="upload.isUploading"
          :on-progress="handleFileUploadProgress"
          :on-success="handleFileSuccess"
          :auto-upload="false"
          drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled/>
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport"/>
            </div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false"
                     v-hasPermi="['marketdata:Curve:download']"
                     style="font-size:12px;vertical-align: baseline;"
                     @click="downTemplate">下载模板
            </el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary"
                     @click="submitFileForm"
                     v-hasPermi="['marketdata:irCurve:import']"
          >确定上传
          </el-button>
          <el-button @click="upload.open = false">取消上传</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Ircurvestrip">
import lodash from 'lodash';
import {
  getIrCrvStripList,
  addIrcCurveStrip,
  uptIrcCurveStrip,
  delIrcCurveStrip,
  getIrCrvStripChartData,
  getCurveList,
  getByIrcCode,
  addIrCurveRates
} from "@/api/curve/ircurve/ircurvestrip";
import baseCombox from "@/xquant/base/baseCombox";
import moment from 'moment'
import xTable from "@/xquant/base/xTable";
import {getToken} from "@/utils/auth";
import IrCurveChart from "@/views/curve/CurveChart";
import Numberinput from '@/xquant/base/number'
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址s
  url: import.meta.env.VITE_APP_BASE_API + "/marketdata/irCurveStrip/importIrCurve"
});
const {proxy} = getCurrentInstance();
import Number from "../../../../xquant/base/number";
import {executeTask} from "../../../../api/pub/pubfunction";
import {
  formartTablePercentP3,
} from '@/utils/numberUtil'
const calTime = ref(null);
const irCrvStripList = ref([]);
const updateOpen = ref(true);
const open = ref(false);
const rows = ref([]);
const compareOpen = ref(false);
const fileName = ref("");
const fileType = ref("");
const loading = ref(false);
const showSearch = ref(true);
const selectObj = ref({});
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const opFlag = ref(false);//true时为修改  false为新增
const btnFlag = ref(true);
const curveCodeList = ref([]);
const router = useRouter();
const data = reactive({
  lineChartData: {},
  form: {
  },
  compareForm: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    ircCode: undefined,
    refSetDate: proxy.getSysDate()
  },
  rules: {
    ircCode: [{required: true, message: "利率曲线不能为空", trigger: "blur"}],
    ircTerm: [{required: true, message: "期限不能为空", trigger: "blur"}, {
      pattern: /^[0-9]*[d,D,y,Y,m,M,w,W]$/, message: '格式错误', trigger: 'blur'
    }],
    ircRate: [{required: true, message: "利率不能为空", trigger: "blur"}],
    begDate: [{required: true, message: "生效日期不能为空", trigger: "blur"}],
  },
  qryRules: {
    ircCode: [{required: true, message: "利率曲线不能为空", trigger: "blur"}],
    refSetDate: [{required: true, message: "计算日期不能为空", trigger: "blur"}]
  },
  compareRules: {
    ircCode: [{required: true, message: "利率曲线不能为空", trigger: "blur"}],
    compareDate: [{required: true, message: "计算日期不能为空", trigger: "blur"}]
  }
});
const {queryParams, form, rules, lineChartData, compareForm, compareRules} = toRefs(data);

/** 表单重置 */
function reset() {
  form.value = {
    ircCode: undefined,
    ircTerm: undefined,
    ircRate: undefined,
    begDate: proxy.getSysDate(),
    endDate: proxy.getSysDate()
  };
  proxy.resetForm("icvstripRef");
}

function handleImport() {
  if(!canWrite()){
    proxy.$modal.alertError("没有权限导入");
    return;
  }
  upload.open = true;
}

function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 查询列表 */
function getList() {
  loading.value = true;
  getIrCrvStripList(queryParams.value).then(response => {
    irCrvStripList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    if(irCrvStripList.value.length>0){
      calTime.value='数据日期: '+irCrvStripList.value[0].begDate;
    }else{
      calTime.value=null;
    }
    //显示曲线
    getIrCrvStripChartData(queryParams.value).then(response => {
      let irCurveRateList = response.msg;
      let obj = curveCodeList.value.find((item) => {
        return item.code === queryParams.value.ircCode;
      });
      proxy.$refs.lineChartForm.setCharData(proxy, '利率曲线', irCurveRateList, 'ircTerm', 'ircRate', queryParams.value.refSetDate + '|' + obj.name, true);
    })
  });
}


/** 搜索按钮操作 */
function handleQuery() {
  if (lodash.isNull(queryParams.value.refSetDate) || proxy.isVoid(queryParams.value.ircCode) || queryParams.value.ircCode == '') {
    btnFlag.value = true;
    irCrvStripList.value = [];
    proxy.$refs.lineChartForm.clearCharData();
    total.value = 0;
    return;
  } else {
    btnFlag.value = false;
  }
  queryParams.value.pageNum = 1;
  getList();
}

/** 对比弹窗*/
function handleCompare() {
  compareForm.value = {
    ircCode: undefined,
    compareDate: proxy.getSysDate()
  };
  proxy.resetForm("icvstripComRef");
  compareOpen.value = true;
}

// 下载模板
function downTemplate() {
  proxy.download("marketdata/irCurveStrip/downloadFile.action", Object.assign({
    fileName, fileType
  }, {fileName: "利率曲线导入模板.xlsx", fileType: "xls,xlsx", businType: 'Ircurve'}), `利率曲线导入模板.xlsx`);
}

function getCurveCodeList() {
  getCurveList().then(response => {
    curveCodeList.value = response.result;
    if (response.result.length > 0) {
      if (typeof(queryParams.value.ircCode) !== "undefined") {
        
      } else {
        queryParams.value.ircCode = response.result[0].code;
      }
      handleQuery();
    }
  });
}

const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].clearFiles();
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
};


const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

onMounted(() => {
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    queryParams.value.ircCode = router.currentRoute.value.query.ircCode
  }
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    queryParams.value.refSetDate = router.currentRoute.value.query.opexDate
  }
  getCurveCodeList();
})

/** 新增按钮操作 */
function handleAdd() {
  if(!canWrite()){
    proxy.$modal.alertError("没有权限新增");
    return;
  }
  reset();
  form.value.ircCode = queryParams.value.ircCode;

  opFlag.value = false;
  open.value = true;
  title.value = "添加利率";
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

function cancelCompare() {
  compareOpen.value = false;
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  selectObj.value = selection.map(item => {
    return {'ircCode': item.ircCode, 'ircTerm': item.ircTerm, 'begDate': item.begDate, 'endDate': item.endDate};
  });
  single.value = selection.length != 1;
  if(selection.length == 1) {
    updateOpen.value = false
    rows.value = selection.map((item) => item);
  }
  if(selection.length != 1) {
    updateOpen.value = true
    rows.value = [];
  }
  multiple.value = !selection.length;
}

/** 修改按钮操作 */
function handleUpdate(row) {
  if(!canWrite()){
    proxy.$modal.alertError("没有权限修改");
    return;
  }
  reset();
  // let param = selectObj.value;
  // if (param.length > 0) {
  //   param = param[0];
  // }
  // getIrCrvStripList(param).then(response => {
  //   form.value = response.rows[0];
  //   open.value = true;
  //   opFlag.value = true;
  //   title.value = "修改曲线定义";
  // });
  title.value = "修改利率";
  data.form = Object.assign({},rows.value[0]);
  data.form.ircRate = data.form.ircRate*100
  open.value = true;
  opFlag.value = true;
}

/**提交对比曲线*/
function submitCompareForm() {
  proxy.$refs["icvstripComRef"].validate(valid => {
    if (valid) {
      //显示曲线
      getIrCrvStripChartData({
        'ircCode': compareForm.value.ircCode,
        'refSetDate': compareForm.value.compareDate
      }).then(response => {
        let irCurveRateList = response.msg;
        let obj = curveCodeList.value.find((item) => {
          return item.code === compareForm.value.ircCode;
        });
        proxy.$refs.lineChartForm.setCharData(proxy, '利率曲线', irCurveRateList, 'ircTerm', 'ircRate', compareForm.value.compareDate + '|' + obj.name, false);
        compareOpen.value = false;
      })
    }
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["icvstripRef"].validate(valid => {
    if (valid) {
      if (opFlag.value == true) {
        open.value = false;
        data.form.ircRate = data.form.ircRate/100
        uptIrcCurveStrip(form.value).then(response => {
          if(response.success){
            proxy.$modal.msgSuccess("修改成功");
            getList();
          }else{
            proxy.$modal.msgWarning(response.msg);
          }

        });
      } else {
        data.form.endDate = '2050-12-31'
        open.value = false;
        data.form.ircRate = data.form.ircRate/100
        addIrCurveRates(form.value).then(response => {
          if(response.success){
            proxy.$modal.msgSuccess("新增成功");
            getList();
          }else{
            proxy.$modal.msgWarning(response.msg);
          }

        });
      }
    }
  });
}

/** 计算按钮操作 */
function handleCal(row) {
  const jobContext = '<?xml version="1.0" encoding="gb2312"?>\n' +
      '<root TYPE="TREE">\n' +
      '  <Parameter>\n' +
      '    <BaseDate DATATYPE="STRING" TYPE="SIMPLE" Caption="计算日期">{baseDate}</BaseDate>\n' +
      '    <Tasks>\n' +
      '      <Task T_CODE="CALC_TERMSTRUCTURE">\n' +
      '        <IRCurve>\n' +
      '          <IsSycCache DATATYPE="INT" Caption="是否同步到缓存" TYPE="SIMPLE" CType="Enum" EnumList="0=否;1=是">1</IsSycCache>\n' +
      '          <CalcCurveType DATATYPE="INT" Caption="计算代码" TYPE="SIMPLE" CType="Enum" EnumList="0=不计算;1=计算全部;2=计算曲线代码集">2</CalcCurveType>\n' +
      '          <CurveCodes DATATYPE="STRING" Caption="曲线代码集" TYPE="ARRAY">\n' +
      '            <V>' + queryParams.value.ircCode + '</V>\n' +
      '          </CurveCodes>\n' +
      '        </IRCurve>\n' +
      '      </Task>\n' +
      '    </Tasks>\n' +
      '    <TGCode DATATYPE="STRING" TYPE="SIMPLE" Caption="任务分组代码">SystemTask</TGCode>\n' +
      '  </Parameter>\n' +
      '</root>';
  let param = lodash.assign({}, {
    id: 6,
    status: '2',
    type: 'PP_TASK',
    typeDesc: '计算任务',
    name: '利率曲线剥离',
    cronExpression: '0 0/1 * * * ?',
    executeBegDate: queryParams.value.refSetDate,
    executeEndDate: queryParams.value.refSetDate,
    context: jobContext
  });
  executeTask(param).then(response => {
    proxy.$modal.msgSuccess("计算任务已发送");
    getList();
    //显示曲线
    getIrCrvStripChartData(queryParams.value).then(response => {
      let irCurveRateList = response.msg;
      let obj = curveCodeList.value.find((item) => {
        return item.code === queryParams.value.ircCode;
      });
      proxy.$refs.lineChartForm.setCharData(proxy, '利率曲线', irCurveRateList, 'ircTerm', 'ircRate', queryParams.value.refSetDate + '|' + obj.name, true);
    })
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  if(!canWrite()){
    proxy.$modal.alertError("没有权限删除");
    return;
  }
  let param = rows.value[0];
  if (param.length > 0) {
    param = param[0];
  }
  proxy.$modal.confirm('是否确认删除这条数据？').then(function () {
    return delIrcCurveStrip(param);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

function canWrite(){
  let obj = curveCodeList.value.find((item) =>{
    return item.code === queryParams.value.ircCode;
  })
  if(obj.ircRight === '1'){
    return false;
  }else {
    return true;
  }
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download("marketdata/irCurveStrip/exportStrip.action", {
    ...queryParams.value
  }, `利率曲线分析${new Date().getTime()}.xlsx`);
}

/** 导出按钮操作 */
function handleExportAll() {
  proxy.download("/marketdata/irCurveStrip/exportStrip.action", Object.assign({
    ...queryParams.value
  }, {pageSize: ''}), `利率曲线剥离${new Date().getTime()}.xlsx`);
}

</script>
